package com.sap.mall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.sap.common.exception.BizCodeEnum;
import com.sap.common.utils.R;
import com.sap.common.vo.MemberRespVo;
import com.sap.mall.auth.feign.MemberFeignClient;
import com.sap.mall.auth.feign.ThirdPartyFeignClient;
import com.sap.mall.auth.vo.UserLoginVo;
import com.sap.mall.auth.vo.UserRegistVo;
import org.apache.http.HttpRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.sap.common.constant.AuthServerConstant.LOGIN_USER;
import static com.sap.common.constant.AuthServerConstant.SMS_CODE_CACHE_PREFIX;

@Controller
public class LoginController {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    MemberFeignClient memberFeignClient;

    @Autowired
    ThirdPartyFeignClient thirdPartyFeignClient;
//    @GetMapping("/login.html")
//    public String loginPage(){
//        return "login";
//    }
//
//    @GetMapping("/reg.html")
//    public String reg(){
//        return "reg";
//    }

    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendCode(@RequestParam("phone") String phone) {
        // 1、接口防刷 todo

        String redisCode = redisTemplate.opsForValue().get(SMS_CODE_CACHE_PREFIX + phone);
        if (!StringUtils.isEmpty(redisCode)) {
            long l = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - l < 60000) {
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMsg());
            }
        }

        //2、验证码再次校验，redis 。 存key-phone value-code
        String code = UUID.randomUUID().toString().substring(0, 5);
        String sub = code + "_" + System.currentTimeMillis();
        redisTemplate.opsForValue().set(SMS_CODE_CACHE_PREFIX + phone, sub, 10, TimeUnit.MINUTES);

        thirdPartyFeignClient.sendSmsCode(phone, code);
        System.out.println("发动验证码===================》" + code);
        return R.ok();
    }


    /**
     * todo 重定向携带数据，利用session与哪里，将数据存放在session中，
     * 只要跳到下一个页面取出这个数据后，session里面的数据就会删掉
     *
     * @param vo
     * @param bindingResult
     * @param redirectAttributes
     * @return
     */
    @PostMapping("/regist")
    public String regist(@Valid UserRegistVo vo, BindingResult bindingResult, RedirectAttributes redirectAttributes) {
        if (bindingResult.hasErrors()) {
            Map<String, String> errors = bindingResult.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            //model.addAttribute("errors",errors);
            // 校验出错，返回注册页
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.mall.com/reg.html";
        }
        // 注册，调用远程服务
        // 1、校验验证吗
        String s = redisTemplate.opsForValue().get(SMS_CODE_CACHE_PREFIX + vo.getPhone());
        if (!StringUtils.isEmpty(s)) {
            if (vo.getCode().equals(s.split("_")[0])) {
                // 删除验证码
                redisTemplate.delete(SMS_CODE_CACHE_PREFIX + vo.getPhone());
                // 验证码通过
                R r = memberFeignClient.regist(vo);
                if (r.getCode() == 0) {
                    return "redirect:http://auth.mall.com/login.html";
                } else {
                    Map<String, String> errors = new HashMap<>();
                    errors.put("msg", r.getData("msg", new TypeReference<String>() {
                    }));
                    redirectAttributes.addFlashAttribute("errors", errors);
                    return "redirect:http://auth.mall.com/reg.html";
                }
            } else {
                Map<String, String> errors = new HashMap<>();
                errors.put("code", "验证码错误");
                redirectAttributes.addFlashAttribute("errors", errors);
                return "redirect:http://auth.mall.com/reg.html";
            }
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码错误");
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.mall.com/reg.html";
        }
    }

    @GetMapping("login.html")
    public String loginPage(HttpSession session) {
        Object attribute = session.getAttribute(LOGIN_USER);
        if (attribute == null) {
            return "login";
        } else {
            return "redirect:http://mall.com";
        }
    }

    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes attributes, HttpSession session) {
        R r = memberFeignClient.login(vo);
        if (r.getCode() == 0) {
            MemberRespVo memberRespVo = r.getData("data", new TypeReference<MemberRespVo>() {
            });
            // TODO: 2/2/2021  1、默认发的令牌，作用域，当前域（解决子域session共享问题） 
            // TODO: 2/2/2021  2、使用json的序列化方式来序列化对象数据到redis
            session.setAttribute(LOGIN_USER, memberRespVo);
            return "redirect:http://mall.com";
        } else {
            HashMap<String, String> errors = new HashMap<>();
            errors.put("msg", r.getData("msg", new TypeReference<String>() {
            }));
            attributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.mall.com/login.html";
        }
    }
}
